package com.meshnetics.gb.stack.mac.primitives;

import com.meshnetics.gb.stack.core.event.StackConfirm;
import com.meshnetics.gb.stack.core.event.StackEvent;
import com.meshnetics.gb.stack.core.event.StackEventType;
import com.meshnetics.gb.stack.core.layer.StackLayer;
import com.meshnetics.gb.stack.mac.RadioMACStackLayer;
import com.meshnetics.gb.stack.mac.type.MACStatus;
import com.meshnetics.gb.stack.mac.type.TypeMACStatus;
import com.meshnetics.gb.type.impl.ByteUtils;
import com.meshnetics.gb.type.impl.zcl.TypeUInt;
import com.meshnetics.gb.type.impl.zcl.UInt;

import java.nio.ByteBuffer;

/**
 * WRITE DESCRIPTION HERE
 *
 * @author AKovylin
 */
public class MACPurgeConfirm extends StackConfirm implements MACReplyOnCommand {
    public static final byte CODE = 0x44;

    private static final byte[] ALLOWED_STATUSES = new byte[]{
            MACStatus.SUCCESS.getCode(),
            MACStatus.INVALID_HANDLE.getCode()
    };

    private final UInt msduHandle;

    public MACPurgeConfirm(ByteBuffer bb, RadioMACStackLayer layer) {
        super("macPurgeConfirm", StackEventType.LDE_TYPE, null, null, layer);
        ByteUtils.ensureNotNull(bb);
        ByteUtils.ensureCapacity(bb, 2);
        this.msduHandle = (UInt) TypeUInt.UINT_8.deserialize(bb);
        MACStatus status = (MACStatus) TypeMACStatus.TYPE.deserialize(bb);
        Utils.checkStatus(status, ALLOWED_STATUSES);
        setStatus(status);
        if (bb.remaining() > 0) {
            throw new IllegalArgumentException("unexpected content of ByteBuffer, " + bb.remaining() + " bytes left");
        }
    }

    public MACPurgeConfirm(MACStatus status, UInt msduHandle) {
        this(status, msduHandle, null);
    }

    public MACPurgeConfirm(MACStatus status, UInt msduHandle, StackLayer source) {
        super("macPurgeConfirm", StackEventType.LDE_TYPE, null, null, source);
        if (status == null) {
            throw new NullPointerException("status is null");
        }
        if (msduHandle == null) {
            throw new NullPointerException("msduHandle is null");
        }
        Utils.checkStatus(status, ALLOWED_STATUSES);
        setStatus(status);
        this.msduHandle = msduHandle.convert(TypeUInt.UINT_8);
    }

    public UInt getMsduHandleType() {
        return msduHandle;
    }

    public Byte getMsduHandle() {
        return (Byte) msduHandle.toObject();
    }

    public boolean isReplyOn(StackEvent se) {
        return se instanceof MACPurgeRequest && this.msduHandle.equals(((MACPurgeRequest) se).getMsduHandleType());
    }

    public String toString() {
        return getName() + '(' + getStatus() + ',' + msduHandle + ')';
    }
}
